from django.http import HttpRequest,HttpResponse
from django.shortcuts import render,redirect


# Create your views here.
from app.models import UserEntity

def list(request:HttpRequest):
    users=UserEntity.objects.all()
    msg='最好的学员'
    return render(request,'app/list.html',locals())

#http://127.0.0.1:8000/user/add?name=%E6%9D%8E%E6%98%8E&age=12&phone=1338766567
def add_user(request:HttpRequest):
    name=request.GET.get('name',None)
    age=request.GET.get('age',0)
    phone = request.GET.get('phone', None)

    #验证参数是否完整
    if not all((name,age,phone)):
        return HttpResponse('<h3 style="color:red">请求参数不完整</h3>',status=400)
    #验证名称是否已经存在数据了
    b1=len(UserEntity.objects.filter(name=name))
    if b1:
        return HttpResponse('<h3 style="color:red">用户已存在</h3>',status=400)
        # IntegrityError

    u1=UserEntity()
    u1.name=name
    u1.age=age
    u1.phone=phone
    u1.save()
    return redirect('/user/list')

def update_user(request:HttpRequest):

    # Model类object.get() 可能会报异常
    id=request.GET.get('id',None)
    if not None:
        return HttpResponse("id 参数必须提供",status=400)

    #表中的这个id用户是否存在
    try:
        user=UserEntity.objects.get(pk=int(id))
        name=request.GET.get('name',None)
        # age=request.GET.get('age',0)
        phone=request.GET.get('phone',None)
        if any((name,phone)):
            if name:
                user.name=name

            if phone:
                user.phone=phone
            user.save()

            return redirect('/user/list')

    except:
        return HttpResponse('%s的用户是不存在的',id)

    pass

def delete_user(request:HttpRequest):
    request.GET.get('id',None)
    if id:
        try:
            user=UserEntity.objects.get(pk=int(id))
            user.delete()
        except:
            return HttpResponse("%s 不存在"%id)
    else:
        return HttpResponse("必须提供id参数")
